package com.lyj.linearalgebra.post.web.servlet;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lyj.linearalgebra.post.domain.Post;
import com.lyj.linearalgebra.post.service.PostService;
import com.lyj.linearalgebra.user.domain.User;

/**
 * Servlet implementation class PostServlet
 */
@WebServlet("/PostServlet")
public class PostServlet extends BaseServlet {
	
	private PostService postService = new PostService();

	public String issue(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		Post form = CommonUtils.toBean(request.getParameterMap(), Post.class);
		User user = (User) request.getSession().getAttribute("session_user");
		form.setUid(user.getUid());
		form.setPid(CommonUtils.uuid());

		String datestyle="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat format=new SimpleDateFormat(datestyle);
		Date time=new Date();
		String nowtime=format.format(time);
		form.setTime(nowtime);
		

		Map<String,String> errors = new HashMap<String,String>();
		
		String title = form.getTitle();
		if(title == null || title.trim().isEmpty()) {
			errors.put("title", "标题不能为空!");
		}
		
		String describe = form.getDescribe();
		if(describe == null || describe.trim().isEmpty()) {
			errors.put("describe", "内容不能为空!");
		}
		
		if(errors.size() > 0) {
			request.setAttribute("errors",errors);
			request.setAttribute("form", form);
			return "f:/myQuestions.jsp";
		}
		
		postService.issue(form);
		
		return myQuestions(request,response);
	}

	public String allQuestions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		request.setAttribute("postList", postService.findAll());
		return "f:/interrogation.jsp";
	}
	
	public String myQuestions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		User user = (User) request.getSession().getAttribute("session_user");
		
		if(user == null) {
			request.setAttribute("result", "尚未登录!");
			return "f:/myQuestions.jsp";
		}
		
		request.setAttribute("postList", postService.findByUid(user.getUid()));
		return "f:/myQuestions.jsp";
	}
	
}
